/**
 * @Title: SignserviceImpl
 * @Package cn.com.yiqi.wsc.service.customer.impl
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-林威
 * @date 2017/2/17 16:48
 * @version V1.0
 */
package cn.com.yiqi.wsc.service.customer.impl;

import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.customer.CustomerSignMapper;
import cn.com.yiqi.wsc.entity.customer.CustomerSign;
import cn.com.yiqi.wsc.entity.customer.CustomerSignExample;
import cn.com.yiqi.wsc.service.customer.CustomerService;
import cn.com.yiqi.wsc.service.point.PointService;
import cn.com.yiqi.wsc.service.point.dataobject.PointOrderDO;
import cn.com.yiqi.wsc.service.sysparams.dataobject.AppParamDO;
import cn.com.yiqi.wsc.service.sysparams.dataobject.SignRuleItem;
import cn.com.yiqi.wsc.util.AppParamUtil;
import cn.com.yiqi.wsc.util.DateUtil;
import cn.com.yiqi.wsc.util.GsonUtil;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 *
 *@ClassName: SignserviceImpl
 * Description: TODO
 * @author 会员系统组-林威
 * @date 2017/2/17 16:48
 *
 */
@Service
public class SignserviceImpl{

    @Autowired
    CustomerSignMapper signDao;

    @Autowired
    CustomerService customerService;

    @Autowired
    PointService pointService;
    /**
     * 连续签到天数
     * */
    public Integer getContinuitySign(Integer userId) {
        CustomerSignExample example = new CustomerSignExample();
        example.setOrderByClause("d_start_time desc");
        example.setLimit(1);
        example.createCriteria().andCustomerIdEqualTo(userId);
        List<CustomerSign> list = signDao.selectByExample(example);
        if(list != null && list.size() > 0){
            return list.get(0).getCount();
        }
        return 0;
    }



    /**
     * 时间段的签到情况
     * */
    public List<String> getSignDetail(Integer userId,Date from, Date to) {

        List<String> signDate = new ArrayList<>();
        List<CustomerSign> list = signDao.findList(userId,from,to);
        if( list!= null && list.size() != 0){
            for (CustomerSign sign:list){
                for (Long i = sign.getStartTime().getTime(); i <= sign.getEndTime().getTime(); i = i + 1000*60*60*24) {
                    signDate.add(DateUtil.dateToString("yyyy-MM-dd",new Date(i)));
                }
            }
        }
        return signDate;
    }

    /**
     * 今天是否已经签到
     * */
    public Boolean hasSign(Integer userId){
        CustomerSign sign = signDao.findlastSign(userId);
        if(sign == null){
           return false;
        }
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(new Date());
        Integer toDay = aCalendar.get(Calendar.DAY_OF_YEAR);

        Calendar sCalendar = Calendar.getInstance();
        sCalendar.setTime(sign.getEndTime());
        Integer lastSign = sCalendar.get(Calendar.DAY_OF_YEAR);
        if( toDay == lastSign){
            return true;
        }
        return false;
    }

    /**
     * 签到
     * */
    @Transactional
    public Result sign(Integer userId) {
        Result re;
        //判断用户是否存在
        re = customerService.isExist(userId);
        if(!ResultUtil.isSuccess(re)){
            return re;
        }

        //判断前一天签到记录
        CustomerSign sign = signDao.findlastSign(userId);
        if(sign == null){
            re.putData("msg","签到成功，获得"+createSign(userId)+"积分");
            return ResultUtil.success(re);
        }
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(new Date());
        Integer toDay = aCalendar.get(Calendar.DAY_OF_YEAR);

        Calendar sCalendar = Calendar.getInstance();
        sCalendar.setTime(sign.getEndTime());
        Integer lastSign = sCalendar.get(Calendar.DAY_OF_YEAR);
        if( toDay.equals(lastSign)){
            re.putData("hasSign",true);
            return  ResultUtil.fail(re,"今天已经签过到！");
        }

        //是否连续签到
        if(toDay - lastSign == 1){
            //连续签到
            sign.setCount(sign.getCount()+1);
            sign.setEndTime(new Date());
            signDao.updateByPrimaryKeySelective(sign);
            //签到送积分
            re.putData("msg","签到成功，获得"+sendPoint(sign)+"积分");
            return ResultUtil.success(re);
        }else {
            //新增签到信息
            re.putData("msg","签到成功，获得"+createSign(userId)+"积分");
            return ResultUtil.success(re);
        }
    }

    /**
     * 新的签到
     *
     */
    private Integer createSign( Integer userId){
        CustomerSign sign = new CustomerSign();
        sign.setCustomerId(userId);
        sign.setStartTime(new Date());
        sign.setEndTime(new Date());
        sign.setCount(1);
        signDao.insertSelective(sign);
        //签到送积分  积分记录
        return sendPoint(sign);
    }

    /**
     * 送积分
     * */
    private Integer sendPoint(CustomerSign sign) {
        List<SignRuleItem> rules = new ArrayList<>();
        String signRule = signDao.findSignRule("SIGNED_RULE");
        rules = GsonUtil.getGson().fromJson(signRule,new TypeToken<List<SignRuleItem>>() {  }.getType());
        List<SignRuleItem> ruleType1 = new ArrayList<>();
        List<SignRuleItem> ruleType2 = new ArrayList<>();
        for (SignRuleItem s:rules){
            if(s.getType() == 1 ){
                ruleType1.add(s);
            } else{
                ruleType2.add(s);
            }
        }
        Collections.sort(ruleType1, new Comparator<SignRuleItem>(){
            public int compare(SignRuleItem o1, SignRuleItem o2) {
                //签到天数降序
                if(o1.getDays() < o2.getDays()){
                    return 1;
                }
                if(o1.getDays() == o2.getDays()){
                    return 0;
                }
                return -1;
            }
        });

        Collections.sort(ruleType2, new Comparator<SignRuleItem>(){
            public int compare(SignRuleItem o1, SignRuleItem o2) {
                //签到天数降序
                if(o1.getDays() < o2.getDays()){
                    return 1;
                }
                if(o1.getDays() == o2.getDays()){
                    return 0;
                }
                return -1;
            }
        });
        Integer total  = 0;
        for (int i = 0; i < ruleType1.size(); i++) {
            if(sign.getCount() >= ruleType1.get(i).getDays()){
                getPoint(sign.getCustomerId(),ruleType1.get(i).getAwardPointMax());
                total += ruleType1.get(i).getAwardPointMax();
                break;
            }
        }
        for (int i = 0; i < ruleType2.size(); i++) {
            if(sign.getCount() % ruleType2.get(i).getDays() == 0){
                int randomPoint = RandomUtils.nextInt(ruleType2.get(i).getAwardPointMin(),ruleType2.get(i).getAwardPointMax());
                getPoint(sign.getCustomerId(),randomPoint);
                total+=randomPoint;
                break;
            }
        }
        return total;
    }

    private void getPoint(Integer userId,Integer point){
        PointOrderDO pdo  = new PointOrderDO();
        pdo.setCustomerId(Long.parseLong(userId+""));
        pdo.setPoint(point);
        pdo.setBizDesc("签到获得");
        pointService.singGetPoint(pdo);
    }
}
